﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;

namespace KiemKe
{
    public partial class FrmThongKeHangDaKiemKe : BasicForms.FrmClose
    {
        public FrmThongKeHangDaKiemKe()
        {
            InitializeComponent();
        }

        private void FrmThongKeHangDaKiemKe_Load(object sender, EventArgs e)
        {
            try
            {
                cmbKyBaoCao.SelectedIndex = 0;

                cmbKho.DataSource = DanhMucKho.Instance.DataView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");

                cmbThoiDiemKhoaSo.DataSource = DanhMucThoiDiemKhoaSo.Instance.DataView;
                cmbThoiDiemKhoaSo.DisplayColumn = "ThoiDiem";
                cmbThoiDiemKhoaSo.ValueColumn = "ID";
                cmbThoiDiemKhoaSo.AddVisibleColumn("ThoiDiem", "Thời điểm");
                cmbThoiDiemKhoaSo.AddVisibleColumn("DienGiai", "Diễn giải");
            }
            catch(Exception ex)
            {
            }

            foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView.Columns)
            {
                column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
            }
            if (AccountingLibs.LocalSettings.HeThong.KhoID is Guid)
                cmbKho.EditValue = AccountingLibs.LocalSettings.HeThong.KhoID;
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                DateTime ngayBatDau = dtNgayBatDau.DateTime;
                DateTime ngayKetThuc = dtNgayBatDau.DateTime;
                switch (cmbKyBaoCao.Text)
                {
                    case "Hôm nay":
                        dtNgayBatDau.Enabled = true;
                        dtNgayKetThuc.Enabled = true;
                        DateTime now = AccountingLibs.CommonLib.GetSystemDateTime();
                        ngayBatDau = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
                        ngayKetThuc = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59);
                        break;
                    case "Tùy chọn":
                        dtNgayBatDau.Enabled = true;
                        dtNgayKetThuc.Enabled = true;
                        ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, 1, 1);
                        ngayKetThuc = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59);
                        break;
                    case "Cả năm":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, 1, 1);
                        ngayKetThuc = new DateTime(AccountingLibs.Config.NamTaiChinh, 12, 31, 23, 59, 59);
                        break;
                    case "Quý I":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, 1, 1);
                        ngayKetThuc = new DateTime(AccountingLibs.Config.NamTaiChinh, 3, 31, 23, 59, 59);
                        break;
                    case "Quý II":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, 4, 1);
                        ngayKetThuc = new DateTime(AccountingLibs.Config.NamTaiChinh, 6, 30, 23, 59, 59);
                        break;
                    case "Quý III":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, 7, 1);
                        ngayKetThuc = new DateTime(AccountingLibs.Config.NamTaiChinh, 9, 30, 23, 59, 59);
                        break;
                    case "Quý IV":
                        dtNgayBatDau.Enabled = false;
                        dtNgayKetThuc.Enabled = false;
                        ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, 10, 1);
                        ngayKetThuc = new DateTime(AccountingLibs.Config.NamTaiChinh, 12, 31, 23, 59, 59);
                        break;
                    default:
                        try
                        {
                            dtNgayBatDau.Enabled = false;
                            dtNgayKetThuc.Enabled = false;
                            string strThang = ((string)cmbKyBaoCao.SelectedItem).Substring(((string)(cmbKyBaoCao.SelectedItem)).LastIndexOf(" "));
                            int thang = int.Parse(strThang);

                            ngayBatDau = new DateTime(AccountingLibs.Config.NamTaiChinh, thang, 1);
                            ngayKetThuc = new DateTime(AccountingLibs.Config.NamTaiChinh, thang,
                                            DateTime.DaysInMonth(AccountingLibs.Config.NamTaiChinh, thang), 23, 59, 59);
                        }
                        catch (Exception ex)
                        {
                            BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
                        }
                        break;
                }
                dtNgayBatDau.DateTime = ngayBatDau;
                dtNgayKetThuc.DateTime = ngayKetThuc;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            BasicForms.FrmProgressBar.StartShowProgress();

            if (cmbKho.Text != "")
            {
                Guid khoID = Guid.Empty;
                DateTime ngayBatDau = dtNgayBatDau.DateTime;
                DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
              
                if (cmbKho.EditValue is Guid && (Guid)cmbKho.EditValue != Guid.Empty) khoID = (Guid)cmbKho.EditValue;

                string kyBaoCao = cmbKyBaoCao.Text;
                if (kyBaoCao == "Cả năm") kyBaoCao = "Năm " + AccountingLibs.Config.NamTaiChinh.ToString();
                else if (kyBaoCao == "Tùy chọn") kyBaoCao = string.Format("Từ ngày {0}/{1}/{2} đến ngày {3}/{4}/{5}",
                                           ngayBatDau.Day, ngayBatDau.Month, ngayBatDau.Year,
                                           ngayKetThuc.Day, ngayKetThuc.Month, ngayKetThuc.Year);

                //BasicForms.FrmProgressBar.StartShowProgress();
                SqlConnection con = new SqlConnection(AccountingLibs.LocalSettings.ConnectString);
                try
                {
                    SqlCommand cmd = con.CreateCommand();
                    con.Open();

                    cmd.CommandText = string.Format("SELECT  D.ID VatTuHangHoaID, D.Ma MaHang, D.Ten TenHang, E.Ten TenNhom, D.DonViTinh,D.TacGia,D.NhaXuatBan, SUM(C.Value1) SoLuongTon, \n" +
                                                    "CASE WHEN SUM(C.Value1) >0 THEN SUM(C.Value3)/SUM(C.Value1)ELSE SUM(C.Value3)  END DonGiaVon , SUM(C.Value3) ThanhTienVon \n " +
                                                    "FROM LoaiChungTu LCT INNER JOIN ChungTu A ON LCT.ID = A.LoaiChungTuID  \n " +
                                                    "    INNER JOIN  KhoanMucChungTu C ON A.ChungTuID = C.ChungTuID  \n " +
                                                    "    INNER JOIN VatTuHangHoa D ON C.VatTuHangHoa1ID = D.ID  \n " +
                                                    "    INNER JOIN NhomVatTuHangHoa E ON D.NhomVatTuHangHoaID = E.ID \n " + 
                                                    "WHERE LCT.Ma = N'PhieuKiemKe'  \n " +
                                                    "AND @ThoiDiemDau <= A.Ngay AND A.Ngay <= @ThoiDiemCuoi  \n" +
                                                    "AND A.Kho1ID = '{0}'  \n" +
                                                    "GROUP BY D.ID, D.Ma,D.Ten,E.Ten,D.GiaBia,D.DonViTinh,D.TacGia,D.NhaXuatBan",
                                                    khoID);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@ThoiDiemDau", ngayBatDau);
                    cmd.Parameters.AddWithValue("@ThoiDiemCuoi", ngayKetThuc);

                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    dsThongKeHangKiemKe.HangKiemKe.Clear();
                    da.Fill(dsThongKeHangKiemKe.HangKiemKe);

                    int total = dsThongKeHangKiemKe.HangKiemKe.Rows.Count;
                    int count = 0;

                    BasicForms.FrmProgressBar.StartShowProgress();

                    //Tinh ton toan bo theo may
                    foreach (DataRow row in dsThongKeHangKiemKe.HangKiemKe.Rows)
                    {
                        try
                        {
                            VatTuHangHoa vthh = DanhMucVatTuHangHoa.Instance.GetByProperty("Ma", row["MaHang"]);
                            TonKho tonToanBo = TonKho.CalculateFromDB(cmd, ngayKetThuc, vthh.ID);
                            if (tonToanBo.SoLuong is decimal) row["TonTheoMay"] = tonToanBo.SoLuong;
                            count ++;
                            BasicForms.FrmProgressBar.Status = "Đã xử lý " + count + "/ " + total;
                        }
                        catch(Exception ex)
                        {
                        }
                    }

                    gridControl.DataSource = dsThongKeHangKiemKe.HangKiemKe;
                }
                catch (Exception ex)
                {
                    BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
                }
                finally
                {
                    con.Close();
                    con = null;
                }
                BasicForms.FrmProgressBar.FinishShowProgress();
            }
            else
            {
                MessageBox.Show("Bạn phải chọn kho hàng!");
            }

            FormatNumberInGridView(gridView);
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            gridControl.ShowPrintPreview();
            //gridView.pr
        }

        private void cmbUpdate_Click(object sender, EventArgs e)
        {
            BasicForms.FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(AccountingLibs.LocalSettings.ConnectString);
            try
            {
                SqlCommand cmd = con.CreateCommand();
                con.Open();

                foreach (DataRow row in dsThongKeHangKiemKe.HangKiemKe.Rows)
                {
                    if (row.RowState != DataRowState.Unchanged)
                    {
                        TonKho tonKho = new TonKho();
                        tonKho.ThoiDiemKhoaSoID = (Guid)cmbThoiDiemKhoaSo.EditValue;
                        tonKho.KhoID = (Guid)cmbKho.EditValue;
                        tonKho.VatTuHangHoaID = (System.Guid)row["VatTuHangHoaID"];
                        tonKho.SoLuong = (decimal)row["SoLuongTon"];
                        tonKho.DonGia = (decimal)row["DonGiaVon"];
                        tonKho.ThanhTien = (decimal)row["ThanhTienVon"];

                        tonKho.InsertOrUpdate2DB(cmd);
                    }
                }

                gridControl.DataSource = dsThongKeHangKiemKe.HangKiemKe;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
            finally
            {
                con.Close();
                con = null;
            }
            BasicForms.FrmProgressBar.FinishShowProgress();
        }
    }
}
